#pragma once
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <functional>

using namespace std;
using func_t = function<string(const string &)>;
int defaultsock = -1;
int backlog = 16;

class TcpServer;
class TcpData
{
public:
    TcpData(TcpServer *s, int sockfd):_s(s),_sockfd(sockfd)
    {}
    ~TcpData()
    {}
    TcpServer *_s;
    int _sockfd;
};

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t func):_port(port), _func(func), _listensock(defaultsock)
    {}

    void InitServer()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if(_listensock < 0)
        {
            cerr << "socket create error" << endl;
            exit(0);
        }
        cout << "socket create success" << endl;

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_listensock, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            cerr << "bind create error" << endl;
            exit(1);
        }
        cout << "bind create success" << endl;

        n = listen(_listensock, backlog);
        if(n < 0)
        {
            cerr << "listen create error" << endl;
            exit(2);
        }
        cout << "listen create success" << endl;
    }

    void Server(int sockfd)
    {
        while(true)
        {
            char buffer[1024];
            ssize_t r = recv(sockfd, buffer, sizeof(buffer)-1, 0);
            if(r > 0)
            {
                buffer[r] = 0;

                string response = _func(buffer);

                send(sockfd, response.c_str(), response.size(), 0);
            }
            else 
            {
                break;
            }
        }
        close(sockfd);
    }

    static void *HandlerTask(void *args)
    {
        pthread_detach(pthread_self());
        TcpData *td = static_cast<TcpData*>(args);
        td->_s->Server(td->_sockfd);
        delete td;
        return nullptr;
    }

    void Loop()
    { 
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensock, (struct sockaddr*)&peer, &len);
            if(sockfd < 0) continue;

            // Server(sockfd);
            TcpData *td = new TcpData(this, sockfd);
            pthread_t tid;
            pthread_create(&tid, nullptr, HandlerTask, td);
        }
    }

    ~TcpServer()
    {
        close(_listensock);
    }

private:
    int _listensock;
    uint16_t _port;
    func_t _func;
};